#!/usr/bin/env python -OO
# -*- coding: utf-8 -*-

# Copyright © 2008,2009 Trust Digital Technology Laboratory, Shanghai Jiao Tong University.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice (including the next
# paragraph) shall be included in all copies or substantial portions of the
# Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
# Author:
#   XING Dong sheng <homer.xing@gmail.com>

from __future__ import with_statement

if __name__ == "__main__":
	exit()

import os, urllib2, sys, traceback, time
from softwareindependent import getArch, ubuntuVersion, freespace, notify

def ownbyme(f):
	os.system(CHOWN+f)

def ownbyroot(f):
	os.system("sudo chown root:root "+f)

def loadSoftwareList():
	global softwarelist, softwaresize
	req = urllib2.Request(SERVER+"list")
	f = urllib2.urlopen(req)
	content = f.readlines()
	f.close()
	for c in content:
		c = c.split()
		if len(c)==3:
			softwarelist[ c[0] ] = c[1]
			softwaresize[ c[0] ] = int(c[2])

def clean():
	os.system("rm %s* -rf"%LOCAL)
	os.system("sudo apt-get clean")

def download(name):
	"如果 LOCAL 中没有软件，那么下载"
	if softwarelist.has_key(name)==False:
		name+=str(getArch())
		if softwarelist.has_key(name)==False:
			name+=("_"+ubuntuVersion())
			if softwarelist.has_key(name)==False:
				notify('BUG!', "http://tdt.sjtu.edu.cn/S/list 没有包含 %s！麻烦告知作者 homer.xing@gmail.com"%name)
				sys.exit(0)
	remote = os.path.join(SERVER, softwarelist[name])
	local = os.path.join(LOCAL, softwarelist[name])
	#如果文件存在，并且大小相同则不重复下载
	if os.path.exists(local):
		here = os.stat(local).st_size
	else:
		here = 0
	if here==softwaresize[name]:
		return local
	need = softwaresize[name] - here
	if freespace(LOCAL)<need:
		notify('狼来了！', "磁盘空间不足，不能下载 %s :("%remote)
		sys.exit(0)
	DIR = softwarelist[name]
	if DIR.find("/")!=-1 :
		DIR = DIR[:DIR.find("/")]
		os.system("mkdir %s%s/"%(LOCAL, DIR) )#创建目录，否则无法下载
	#Try Infinity times, Timeout=3 seconds,
	if os.system("wget --tries=0 --timeout=3 %s -O %s" % (remote,local) ) !=0:
		notify('BUG!', "BUG! 不能下载%s! 麻烦告知作者 homer.xing@gmail.com "%remote)
		exit()
	return local

def needsetaptsource():
	#FIXME
	return True

def setaptsource():
	version = ubuntuVersion()
	version = {'9.04':'jaunty', '8.10':'hardy'}[version]
	content = """#Shanghai Jiao Tong Univ.
deb http://ftp.sjtu.edu.cn/ubuntu/ jaunty main restricted universe multiverse
deb http://ftp.sjtu.edu.cn/ubuntu/ jaunty-backports restricted universe multiverse
deb http://ftp.sjtu.edu.cn/ubuntu/ jaunty-proposed main restricted universe multiverse
deb http://ftp.sjtu.edu.cn/ubuntu/ jaunty-security main restricted universe multiverse
deb http://ftp.sjtu.edu.cn/ubuntu/ jaunty-updates main restricted universe multiverse
deb-src http://ftp.sjtu.edu.cn/ubuntu/ jaunty main restricted universe multiverse
deb-src http://ftp.sjtu.edu.cn/ubuntu/ jaunty-backports main restricted universe multiverse
deb-src http://ftp.sjtu.edu.cn/ubuntu/ jaunty-proposed main restricted universe multiverse
deb-src http://ftp.sjtu.edu.cn/ubuntu/ jaunty-security main restricted universe multiverse
deb-src http://ftp.sjtu.edu.cn/ubuntu/ jaunty-updates main restricted universe multiverse
""".replace("jaunty", version)
	ownbyme("/etc/apt/sources.list")
	with open("/etc/apt/sources.list", "w") as f:
		f.write(content)
	ownbyroot("/etc/apt/sources.list")

def onfail(returnvalue):
    global log
    if returnvalue!=0:
        if log==None:
            log = open( os.path.join(logdir,'failed.log') , 'a+')
            log.write('\n' + time.ctime(time.time()) + '\n')

        log.write('Failed! Return Value=%d\n'%returnvalue)
        traceback.print_stack(None, None, log)
        log.flush()
        return True

def execute(cmd):
    ret = os.system(cmd)
    onfail(ret)
    return ret==0

def install(package):
	ret = os.system('sudo apt-get install %s -qq'%package)
	onfail(ret)
	return ret==0

global choice
global inited
try:
	inited
except:
	inited=True

	softwarelist = {} #在服务器上，软件名与对应的文件名
	softwaresize = {} #在服务器上，软件名与对应的文件的字节数
	SERVER="http://tdt.sjtu.edu.cn/S/"
	HOME = os.getenv("HOME") #用户主目录
	USER = os.getenv("USER")
	CHOWN = "sudo chown %s:%s "%(USER, USER)
	DESKTOP = os.path.join(HOME, "Desktop/") #用户桌面
	WINEROOT = os.path.join(HOME, ".wine/drive_c/") #用户的wine的C驱动器目录
	LOCAL = "/var/cache/ubuntueasysetuper/"
	choice = ""
	loadSoftwareList()
	os.system("sudo mkdir %s -p"%LOCAL)
	ownbyme(LOCAL)
	log = None
	FILES = os.path.dirname( os.path.abspath(sys.argv[0]) ) + '/Files/'
	logdir = os.path.dirname( os.path.abspath(sys.argv[0]) )
